package com.caszx.chargingpile.fragment.user;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.TextView;
import com.alibaba.fastjson.JSONException;
import com.app.base.fragment.BaseFragment;
import com.app.utils.DipPxUtil;
import com.app.utils.DiskUser;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.activity.UserBindVipActivity;
import com.caszx.chargingpile.activity.SettingActivity;
import com.caszx.chargingpile.activity.UserAccountActivity;
import com.caszx.chargingpile.activity.UserHistoryOrderActivity;
import com.caszx.chargingpile.activity.UserMessageActivity;
import com.caszx.chargingpile.activity.UserRechargeActivity;
import com.caszx.chargingpile.activity.UserSignInActivity;
import com.caszx.chargingpile.activity.WebViewActivity;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;

import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;

/**
 *
 */
public class UserHomeFragment extends BaseFragment implements View.OnClickListener {


    private TextView btn_sign_in;
    private TextView txt_name;
    private View center_line;
    private TextView txt_remain;
    private TextView txt_consume;
    private TextView txt_menu_recharge;
    private TextView txt_menu_user;
    private TextView txt_menu_bind;
    private TextView txt_menu_order;
    private TextView txt_menu_msg;
    private TextView txt_menu_setting;
    private TextView txt_menu_about;
    private TextView txt_server;
    DecimalFormat decimalFormat = new DecimalFormat("##.##");

    public static UserHomeFragment newInstance() {
        UserHomeFragment fragment = new UserHomeFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected View initView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_user_home, null);
        findViewById(view);
        initListener();
        drawTextView();
        return view;
    }

    private void findViewById(View view) {
        btn_sign_in = (TextView) view.findViewById(R.id.btn_sign_in);
        txt_name = (TextView) view.findViewById(R.id.txt_name);
        txt_remain = (TextView) view.findViewById(R.id.txt_remain);
        center_line = view.findViewById(R.id.center_line);
        txt_consume = (TextView) view.findViewById(R.id.txt_consume);

        txt_menu_recharge = (TextView) view.findViewById(R.id.txt_menu_recharge);
        txt_menu_user = (TextView) view.findViewById(R.id.txt_menu_user);
        txt_menu_bind = (TextView) view.findViewById(R.id.txt_menu_bind);
        txt_menu_order = (TextView) view.findViewById(R.id.txt_menu_order);
        txt_menu_msg = (TextView) view.findViewById(R.id.txt_menu_msg);
        txt_menu_setting = (TextView) view.findViewById(R.id.txt_menu_setting);
        txt_menu_about = (TextView) view.findViewById(R.id.txt_menu_about);
        txt_server = (TextView) view.findViewById(R.id.txt_server);
    }

    private void initListener() {
        btn_sign_in.setOnClickListener(this);
        txt_menu_recharge.setOnClickListener(this);
        txt_menu_user.setOnClickListener(this);
        txt_menu_bind.setOnClickListener(this);
        txt_menu_order.setOnClickListener(this);
        txt_menu_msg.setOnClickListener(this);
        txt_menu_setting.setOnClickListener(this);
        txt_menu_about.setOnClickListener(this);
    }

    private void drawTextView() {

        int bound = DipPxUtil.dip2px(getContext(), 20);
        Drawable right_arrow = getResources().getDrawable(R.drawable.selector_right_arrow);
        right_arrow.setBounds(0, 0, bound, bound);

        Drawable menu_00 = getResources().getDrawable(R.mipmap.user_icon_recharge);
        menu_00.setBounds(0, 0, bound, bound);
        txt_menu_recharge.setCompoundDrawables(menu_00, null, right_arrow, null);

        Drawable menu_01 = getResources().getDrawable(R.mipmap.user_icon_me);
        menu_01.setBounds(0, 0, bound, bound);
        txt_menu_user.setCompoundDrawables(menu_01, null, right_arrow, null);

        Drawable menu_02 = getResources().getDrawable(R.mipmap.user_icon_card);
        menu_02.setBounds(0, 0, bound, bound);
        txt_menu_bind.setCompoundDrawables(menu_02, null, right_arrow, null);

        Drawable menu_03 = getResources().getDrawable(R.mipmap.user_icon_order);
        menu_03.setBounds(0, 0, bound, bound);
        txt_menu_order.setCompoundDrawables(menu_03, null, right_arrow, null);

        Drawable menu_04 = getResources().getDrawable(R.mipmap.user_icon_mail);
        menu_04.setBounds(0, 0, bound, bound);
        txt_menu_msg.setCompoundDrawables(menu_04, null, right_arrow, null);

        Drawable menu_05 = getResources().getDrawable(R.mipmap.user_icon_set);
        menu_05.setBounds(0, 0, bound, bound);
        txt_menu_setting.setCompoundDrawables(menu_05, null, right_arrow, null);

        Drawable menu_06 = getResources().getDrawable(R.mipmap.user_icon_about);
        menu_06.setBounds(0, 0, bound, bound);
        txt_menu_about.setCompoundDrawables(menu_06, null, right_arrow, null);

        SpannableStringBuilder builder = new SpannableStringBuilder("客服热线 ");
        builder.append(getActivity().getResources().getString(R.string.server_phone));
        int start = builder.length();
        builder.append("\n(服务时间 ");
        builder.append(getActivity().getResources().getString(R.string.server_time)).append(")");
        builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray5)), start, builder.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        txt_server.setText(builder);
        txt_server.getPaint().setUnderlineText(false);

    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        String token = DiskUser.getStringValueByKey(getContext(), "token");
        String acount = DiskUser.getStringValueByKey(getContext(), "acount");
        if (TextUtils.isEmpty(token)) {
            btn_sign_in.setVisibility(View.VISIBLE);
            txt_name.setVisibility(View.GONE);
            txt_remain.setVisibility(View.GONE);
            center_line.setVisibility(View.GONE);
            txt_consume.setVisibility(View.GONE);
        } else {
            btn_sign_in.setVisibility(View.GONE);
            txt_name.setVisibility(View.VISIBLE);
            txt_remain.setVisibility(View.VISIBLE);
            center_line.setVisibility(View.GONE);
            txt_consume.setVisibility(View.GONE);
            txt_name.setText(acount);
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        String token = null;
        switch (v.getId()) {
            case R.id.btn_sign_in:
                intent = new Intent(getActivity(), UserSignInActivity.class);
                break;
            case R.id.txt_menu_recharge:
                token = DiskUser.getStringValueByKey(getActivity(), "token");
                if (TextUtils.isEmpty(token)) {
                    intent = new Intent(getActivity(), UserSignInActivity.class);
                    getActivity().startActivity(intent);
                    return;
                }

                intent = new Intent(getActivity(), UserRechargeActivity.class);
                break;
            case R.id.txt_menu_user:
                intent = new Intent(getActivity(), UserAccountActivity.class);
                break;
            case R.id.txt_menu_bind:
                token = DiskUser.getStringValueByKey(getActivity(), "token");
                if (TextUtils.isEmpty(token)) {
                    intent = new Intent(getActivity(), UserSignInActivity.class);
                    getActivity().startActivity(intent);
                    return;
                }

                intent = new Intent(getActivity(), UserBindVipActivity.class);
                break;

            case R.id.txt_menu_order:
                token = DiskUser.getStringValueByKey(getActivity(), "token");
                if (TextUtils.isEmpty(token)) {
                    intent = new Intent(getActivity(), UserSignInActivity.class);
                    getActivity().startActivity(intent);
                    return;
                }

                intent = new Intent(getActivity(), UserHistoryOrderActivity.class);
                break;


            case R.id.txt_menu_msg:
                token = DiskUser.getStringValueByKey(getActivity(), "token");
                if (TextUtils.isEmpty(token)) {
                    intent = new Intent(getActivity(), UserSignInActivity.class);
                    getActivity().startActivity(intent);
                    return;
                }
                intent = new Intent(getActivity(), UserMessageActivity.class);
                break;

            case R.id.txt_menu_setting:
                intent = new Intent(getActivity(), SettingActivity.class);
                break;
            case R.id.txt_menu_about:
                intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("WEBURL",ConstantUrl.APP_ABOUT);
                intent.putExtra("title","关于");
                break;
        }

        if (intent == null) return;
        getActivity().startActivity(intent);
    }


    private void upDataUser(JSONObject jsonObject) {
        if (jsonObject != null) {
            txt_remain.setText("余额" + decimalFormat.format(jsonObject.optDouble("balance")));
            txt_consume.setText("消费" + decimalFormat.format(jsonObject.optDouble("countCost")));
            int unReadNo = jsonObject.optInt("unReadNo");
            if (unReadNo > 0) {
                txt_menu_msg.setText("系统消息(" + unReadNo + ")");
            } else {
                txt_menu_msg.setText("系统消息");
            }
        } else {
            txt_remain.setText("余额");
            txt_consume.setText("消费");
            txt_menu_msg.setText("系统消息");
        }
    }

    public void onEvent(String action) {
        if (EventBusAction.ACTION_SING_IN.equals(action)) {
            //登录
        } else if (EventBusAction.ACTION_SING_OUT.equals(action)) {
            //退出
            upDataUser(null);
        } else if (EventBusAction.ACTION_USER_CANCEL_RESER.equals(action)) {
            //取消订单
            getUserInfo();
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void getUserInfo() {
        OkHttpUtils.getInstance().cancelTag(this);
        HashMap<String, String> params = new HashMap<>();
        String token = DiskUser.getStringValueByKey(getActivity(), "token");
        params.put("token", token);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_DETAIL)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        //showSnackbarMsg(getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                upDataUser(null);
                            } else {
                                try {
                                    upDataUser(response);
                                } catch (JSONException e) {

                                }
                            }
                        }
                    }
                });
    }
}
